/*
 * 文件名：CarryLawcaseController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wangw
 * 修改时间：2020年3月31日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.la.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.la.domain.CarryLawcaseDomain;
import top.infopub.mgr.la.service.CarryLawcaseService;
import top.infopub.mgr.la.service.SueLawcaseService;
import top.infopub.mgr.la.service.UpwardLawcaseService;
import top.infopub.mgr.la.vo.CarryLawcaseVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.la.CarryLawcaseAtt;
import top.infopub.model.la.SueLawcase;
import top.infopub.model.la.UpwardLawcase;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.github.pagehelper.Page;


/**
 * 执行案件
 * @author wangw
 * @version 2020年3月31日
 * @see CarryLawcaseController
 * @since
 */
@Controller
@RequestMapping("/carryLawcase")
public class CarryLawcaseController extends GenericFlowController {

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private UpwardLawcaseService upwardLawcaseService;
    
    @Autowired
    private SueLawcaseService sueLawcaseService;

    @Autowired
    private CarryLawcaseService carryLawcaseService;

    /**
     * 执行案件列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "la/lay-carryLawcase-list";
    }

    /**
     * 执行案件列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<CarryLawcaseDomain> queryDataByCondition(CarryLawcaseVo carryLawcaseVo,
                                                        ParamPage paramPage) {
        Page<CarryLawcaseDomain> page = new Page<CarryLawcaseDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (carryLawcaseVo.getEndDate() != null) {
            carryLawcaseVo.setEndDate(DateUtils.addDays(carryLawcaseVo.getEndDate(), 1));
        }
        //查询时，执行申请结束日期增加一天
        if (carryLawcaseVo.getCarryEndDate() != null) {
            carryLawcaseVo.setCarryEndDate(DateUtils.addDays(carryLawcaseVo.getCarryEndDate(), 1));
        }
        page = carryLawcaseService.selectByDomainWhere(page, carryLawcaseVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 执行案件-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<CarryLawcaseDomain> queryMyCheckDataByCondition(CarryLawcaseVo carryLawcaseVo,
                                                               ParamPage paramPage) {
        Page<CarryLawcaseDomain> page = new Page<CarryLawcaseDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (carryLawcaseVo.getEndDate() != null) {
            carryLawcaseVo.setEndDate(DateUtils.addDays(carryLawcaseVo.getEndDate(), 1));
        }
        //查询时，执行申请结束日期增加一天
        if (carryLawcaseVo.getCarryEndDate() != null) {
            carryLawcaseVo.setCarryEndDate(DateUtils.addDays(carryLawcaseVo.getCarryEndDate(), 1));
        }
        carryLawcaseVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = carryLawcaseService.selectMyCheckByDomainWhere(page, carryLawcaseVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 执行案件-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //查询可执行案件的记录
        List<SueLawcase> sueLawcases = sueLawcaseService.selectUsableCarry();
        request.setAttribute("sueLawcases", sueLawcases);
        return "la/lay-carryLawcase-add";
    }
    
    /**
     * 根据起诉案件id查询上诉案件记录或者起诉案件记录
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLawcaseById")
    @ResponseBody
    public Map<String, Object> getLawcaseById(String sueLawcaseId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //查询上诉案件记录
            Map<String, Object> mapWhere = new HashMap<String, Object>();
            mapWhere.put("sueLawcaseId", sueLawcaseId);
            mapWhere.put("processStatus", "9");
            mapWhere.put("orderCondition", "ADD_TIME desc");
            List<UpwardLawcase> upwardLawcases = upwardLawcaseService.selectByMapWhere(mapWhere);
            if (CollectionUtils.isNotEmpty(upwardLawcases)) {
                map.put("lawcase", upwardLawcases.get(0));
            }else {//没有上诉案件记录，则查询起诉案件记录
                SueLawcase sueLawcase = sueLawcaseService.selectByPrimaryKey(sueLawcaseId);
                map.put("lawcase", sueLawcase);
            }
        }
        catch (Exception e) {
            log.error("查询上诉案件记录或者起诉案件记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据id查询执行案件详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 执行案件Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        CarryLawcaseVo carryLawcase = carryLawcaseService.queryById(id);
        map.put("carryLawcase", carryLawcase);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, carryLawcase.getProcessId());
        return new ModelAndView("la/lay-carryLawcase-detail", map);
    }

    /**
     * 新增执行案件
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(HttpServletRequest request,CarryLawcaseVo carryLawcase) {
        String[] fileAtt1 = request.getParameterValues("fileAtt1");
        String[] fileAtt2 = request.getParameterValues("fileAtt2");
        String[] fileAtt3 = request.getParameterValues("fileAtt3");
        if (fileAtt1 == null || fileAtt1.length < 1) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("生效法律文书未上传");
        }
        if (fileAtt2 == null || fileAtt2.length < 1) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("执行申请书未上传");
        }
        //执行案件表处理
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        carryLawcase.setId(id);
        carryLawcase.setAddBy(vo.getId());
        carryLawcase.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("la_carry_lawcase");
        carryLawcase.setCodes(code);
        // 处理processId
        carryLawcase.setProcessId(IdFactory.getUUIDUpper());
        carryLawcase.setProcessStatus("1");//审批中
        carryLawcase.setUptBy(vo.getId());
        carryLawcase.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //上传附件
        List<CarryLawcaseAtt> carryLawcaseAtts = new ArrayList<CarryLawcaseAtt>();
        //生效法律文书
        if (fileAtt1 != null) {
            for (String file : fileAtt1) {
                CarryLawcaseAtt carryLawcaseAtt = createFileAtt(vo, id, file);
                carryLawcaseAtts.add(carryLawcaseAtt);
            }
        }
        //执行申请书
        if (fileAtt2 != null) {
            for (String file : fileAtt2) {
                CarryLawcaseAtt carryLawcaseAtt = createFileAtt(vo, id, file);
                carryLawcaseAtts.add(carryLawcaseAtt);
            }
        }
        //其他附件
        if (fileAtt3 != null) {
            for (String file : fileAtt3) {
                CarryLawcaseAtt carryLawcaseAtt = createFileAtt(vo, id, file);
                carryLawcaseAtts.add(carryLawcaseAtt);
            }
        }
        carryLawcaseService.saveCarryLawcase(carryLawcase, carryLawcaseAtts);
        LogUtil.bizLog(LogModelType.OTHER, AcctionType.ADD, "法务管理 -执行案件：案件名称=" + carryLawcase.getLawcaseName(), null);
        return RspVo.getSuccessResponse();
    }

    private CarryLawcaseAtt createFileAtt(AuthorizationVO vo, String carryLawcaseId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        CarryLawcaseAtt fileAtt = new CarryLawcaseAtt();
        fileAtt.setTypes(fileAttStr[0]);
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setCarryLawcaseId(carryLawcaseId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "carryLawcaseAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

}
